<template>
  <el-dialog
    v-model="dialogVisible"
    title="申请关闭"
    width="600px"
    @close="handleClose"
  >
    <div v-if="permitData" class="close-dialog">
      <el-alert
        title="关闭申请说明"
        type="warning"
        :closable="false"
        style="margin-bottom: 20px"
      >
        <p>许可证编号：{{ permitData.permitNumber }}</p>
        <p>请确认作业已完成或需要提前关闭</p>
      </el-alert>
      
      <el-form
        :model="closeForm"
        :rules="closeRules"
        ref="closeFormRef"
        label-width="120px"
      >
        <el-form-item label="关闭原因" prop="reason">
          <el-select v-model="closeForm.reason" placeholder="请选择关闭原因" style="width: 100%">
            <el-option label="作业已完成" value="completed" />
            <el-option label="作业取消" value="cancelled" />
            <el-option label="安全原因" value="safety_issue" />
            <el-option label="设备故障" value="equipment_failure" />
            <el-option label="其他原因" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="关闭说明" prop="description">
          <el-input
            v-model="closeForm.description"
            type="textarea"
            :rows="4"
            placeholder="请详细说明关闭原因"
          />
        </el-form-item>
        
        <el-form-item label="实际结束时间" prop="actualEndTime">
          <el-date-picker
            v-model="closeForm.actualEndTime"
            type="datetime"
            placeholder="选择实际结束时间"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        
        <el-form-item label="完工照片" prop="photos">
          <el-upload
            v-model:file-list="closeForm.photos"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="5"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            最多上传5张照片，支持JPG、PNG格式
          </div>
        </el-form-item>
        
        <el-form-item label="安全确认" prop="safetyConfirmed">
          <el-checkbox-group v-model="closeForm.safetyConfirmed">
            <el-checkbox value="equipment_cleaned">设备已清理</el-checkbox>
            <el-checkbox value="area_cleared">作业区域已清理</el-checkbox>
            <el-checkbox value="safety_measures_removed">安全措施已移除</el-checkbox>
            <el-checkbox value="personnel_evacuated">人员已撤离</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="质量检查" prop="qualityCheck">
          <el-radio-group v-model="closeForm.qualityCheck">
            <el-radio value="passed">质量检查通过</el-radio>
            <el-radio value="failed">质量检查未通过</el-radio>
            <el-radio value="pending">待检查</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="closeForm.qualityCheck === 'failed'" label="质量问题" prop="qualityIssues">
          <el-input
            v-model="closeForm.qualityIssues"
            type="textarea"
            :rows="3"
            placeholder="请描述质量问题"
          />
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        提交申请
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'

interface PermitData {
  id: number
  permitNumber: string
}

interface CloseForm {
  reason: string
  description: string
  actualEndTime: string
  photos: any[]
  safetyConfirmed: string[]
  qualityCheck: string
  qualityIssues: string
}

interface Props {
  modelValue: boolean
  permitData: PermitData | null
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const closeFormRef = ref<FormInstance>()
const submitting = ref(false)

const closeForm = reactive<CloseForm>({
  reason: '',
  description: '',
  actualEndTime: '',
  photos: [],
  safetyConfirmed: [],
  qualityCheck: '',
  qualityIssues: ''
})

const closeRules: FormRules = {
  reason: [
    { required: true, message: '请选择关闭原因', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入关闭说明', trigger: 'blur' }
  ],
  actualEndTime: [
    { required: true, message: '请选择实际结束时间', trigger: 'change' }
  ],
  safetyConfirmed: [
    { required: true, message: '请确认安全措施', trigger: 'change' }
  ],
  qualityCheck: [
    { required: true, message: '请选择质量检查结果', trigger: 'change' }
  ],
  qualityIssues: [
    { required: true, message: '请描述质量问题', trigger: 'blur' }
  ]
}

// 禁用未来的日期
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

// 提交申请
const handleSubmit = async () => {
  if (!closeFormRef.value) return
  
  try {
    await closeFormRef.value.validate()
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    ElMessage.success('关闭申请提交成功')
    emit('success')
    handleClose()
  } catch (error: any) {
    ElMessage.error(error.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  closeForm.reason = ''
  closeForm.description = ''
  closeForm.actualEndTime = ''
  closeForm.photos = []
  closeForm.safetyConfirmed = []
  closeForm.qualityCheck = ''
  closeForm.qualityIssues = ''
  closeFormRef.value?.resetFields()
}

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (!visible) {
    handleClose()
  }
})
</script>

<style lang="scss" scoped>
.close-dialog {
  .el-form-item {
    margin-bottom: 20px;
  }
  
  .upload-tip {
    font-size: 12px;
    color: #999;
    margin-top: 8px;
  }
}
</style>

